package com.bxait.toymail.order.web;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.bxait.com.exception.order.NoStockException;
import com.bxait.com.utils.PageUtils;
import com.bxait.com.utils.R;
import com.bxait.toymail.order.config.AlipayConfig;
import com.bxait.toymail.order.config.AlipayTemplate;
import com.bxait.toymail.order.service.OrderService;
import com.bxait.toymail.order.vo.OrderConfirmVo;
import com.bxait.toymail.order.vo.OrderSubmitVo;
import com.bxait.toymail.order.vo.PayVo;
import com.bxait.toymail.order.vo.SubmitOrderResponseVo;
import jdk.nashorn.internal.objects.annotations.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

/*
@description:
@ClassName ViewController
@author Chen
@create 2023-05-13 10:16
@Version 1.0
*/
@Slf4j
@Controller
public class ViewController {
    @Resource
    @Qualifier("orderService")
    OrderService orderService;

    @Resource
    AlipayTemplate alipayTemplate;

    @Resource
    AlipayConfig alipayConfig;


    /*
     * @param vo
     * @param model
     * @param redirectAttributes
     * @==============History===============<br/>
     * @Description //   下单功能
     * @Date 2023/5/13 2023/5/13
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return java.lang.String
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo vo, Model model, RedirectAttributes redirectAttributes){
        try {
            SubmitOrderResponseVo responseVo = orderService.submitOrder(vo);
            responseVo.setTotal(vo.getPayPrice());
            //下单失败回到订单确认页重新确认订单信息
            System.out.println("订单提交的数据..."+vo);
            if(responseVo.getCode() == 0){
                // 下单成功来到支付选择页
                model.addAttribute("submitOrderResp",responseVo);
                return  "pay";
            }else{
                String msg = "下单失败；";
                switch (responseVo.getCode()){
                    case 1:  msg += "订单信息过期，请刷新再次提交"; break;
                    case 2: msg+= "订单商品价格发生变化，请确认后再次提交"; break;
                    case 3: msg+="库存锁定失败，商品库存不足"; break;
                }
                redirectAttributes.addFlashAttribute("msg",msg);
                // 下单失败,去订单页面
                return "redirect:http://order.toymail.com/toTrade";
            }
        }catch (Exception e){
            if(e instanceof NoStockException){
                String message = ((NoStockException) e).getMessage();
                redirectAttributes.addFlashAttribute("msg",message);
            }
            // 出现异常回到订单页面
            return "redirect:http://order.toymail.com/toTrade";
        }
    }

    /*
     * @param model
     * @param request
     * @==============History===============<br/>
     * @Description //   处理购物车结算请求
     * @Date 2023/5/13 2023/5/13
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return java.lang.String
     */
    @GetMapping("/toTrade")
    public String toTrade(Model model, HttpServletRequest request) throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo =  orderService.confirmOrder();
        model.addAttribute("orderConfirmData",confirmVo);
        //展示订单确认的数据
        return "confirm";
    }

    /*
     * @param page
     * @==============History===============<br/>
     * @Description //   页面跳转
     * @Date 2023/5/13 2023/5/13 
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return java.lang.String
     */
    @GetMapping("/{page}.html")
    public String listPage(@PathVariable("page") String page){
        return page;
    }

    
    /*
     * @param 
     * @==============History===============<br/>
     * @Description // 支付功能的实现，获取当前订单的支付信息
     * @Date 2023/5/18 2023/5/18 
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return java.lang.String
     */
//    @ResponseBody
//    @GetMapping(value = "/payOrder",produces = MediaType.TEXT_HTML_VALUE)
//    public String pay(@RequestParam("orderSn") String orderSn) throws AlipayApiException {
//        log.error("orderSn{}",orderSn);
//        PayVo payVo = orderService.getOrderPay(orderSn);
//        // 返回的是一个页面。将此页面直接交给浏览器就行
//        String pay = alipayTemplate.pay(payVo);
//        return pay;
//    }

    /*
     * @param
     * @==============History===============<br/>
     * @Description // 支付功能的实现，获取当前订单的支付信息
     * @Date 2023/5/18 2023/5/18
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return java.lang.String
     */
    @GetMapping(value = "/payOrder",produces = MediaType.TEXT_HTML_VALUE)
    @ResponseBody
    public String gotoPayPage(@RequestParam("orderSn") String orderSn){
        AlipayTradePagePayRequest pagePayRequest=new AlipayTradePagePayRequest();
        //SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
        AlipayClient alipayClient = new DefaultAlipayClient(
                alipayConfig.gatewayUrl,
                alipayConfig.app_id,
                alipayConfig.merchant_private_key,
                alipayConfig.format,
                alipayConfig.charset,
                alipayConfig.alipay_public_key,
                alipayConfig.sign_type);

        pagePayRequest.setReturnUrl(alipayConfig.return_url);
        pagePayRequest.setNotifyUrl(alipayConfig.notify_url);

        // 订单模型
        String productCode = "FAST_INSTANT_TRADE_PAY";
        PayVo payVo = orderService.getOrderPay(orderSn);
        AlipayTradePayModel model = new AlipayTradePayModel();
        model.setOutTradeNo(payVo.getOut_trade_no());
        model.setProductCode(productCode);
        model.setTotalAmount(payVo.getTotal_amount());
        model.setSubject(payVo.getSubject());
        model.setBody(payVo.getBody());
        pagePayRequest.setBizModel(model);
        //请求
        String form = "";
        try {
            AlipayTradePagePayResponse payResponse = alipayClient.pageExecute(pagePayRequest);
            form = payResponse.getBody();
            return form;
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("支付宝二维码数据生成失败");
        }

    }


    /**
     * 订单分页查询
     * @param pageNum
     * @param model
     * @return
     */
    @GetMapping("/memberOrder.html")
    public String memberOrderPage(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                                  Model model, HttpServletRequest request){
        //查出当前登录的用户的所有订单列表数据
        Map<String,Object> params =new HashMap<>();
        params.put("page",pageNum.toString());
        PageUtils page = orderService.queryPageWithItem(params);
        R r = R.ok().put("page", page);
        System.out.println(JSON.toJSONString(r));
        model.addAttribute("orders",r);
        return "list";
    }


}
